<template>
  <el-row :gutter="10">
    <el-col v-for="(label, index) in labels" :key="index" :span="2" @click="selectLabel(index)">
      <div class="yesterday-label" :class="{ 'active': selectedLabel === index }">{{ label }}</div>
    </el-col>
    <el-col :span="6">
      <div class="selected-time">已选时间：
        {{ begin }} 至
        {{ end }}</div>
    </el-col>
    <el-col :span="2" :offset="6">
      <el-popconfirm title="是否确认导出最近30天运营数据?" width="200px"
      @confirm="handleConfirm">
        <template #reference>
          <el-button class="export-btn">
            数据导出
            <el-icon class="el-icon--right">
              <Download />
            </el-icon>
          </el-button>
        </template>
      </el-popconfirm>

    </el-col>
  </el-row>

  <el-row :gutter="20">
    <el-col :span="12">
      <div class="grid-content">
        <!-- 营业额统计 -->
        <div id="chart-container" class="chart-container"></div>
      </div>
    </el-col>
    <el-col :span="12">
      <div class="grid-content">
        <!-- 用户统计 -->
        <div id="usermain" class="chart-container"></div>
      </div>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="12">
      <div class="grid-content">
        <!-- 订单统计 -->
        <div id="ordermain" class="chart-container"></div>
      </div>
    </el-col>
    <el-col :span="12">
      <div class="grid-content">
        <!-- 预约统计排名TOP10 -->
        <div id="top" class="chart-container"></div>
      </div>
    </el-col>
  </el-row>
</template>

<script setup>
import { turnoverStatistics, userStatistics, ordersStatistics, top10, exportInfor } from '@/api/report';
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';


const labels = ['昨日', '7日', '30日', '本周', '本月'];
const selectedLabel = ref(1);
const begin = ref(null)
const end = ref(null)

const handleConfirm = async () => {
  const { data } = await exportInfor() // 调用接口导出数据
  let url = window.URL.createObjectURL(data) // 创建一个object URL
  var a = document.createElement('a') // 创建一个a标签
  document.body.appendChild(a) // 将a标签添加到body中
  a.href = url // 设置a标签的href属性
  a.download = '运营数据统计报表.xlsx' // 设置a标签的download属性
  a.click() // 点击a标签，下载文件
  window.URL.revokeObjectURL(url) // 释放object URL
};

const formatDateToString = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
  const day = String(date.getDate()).padStart(2, '0'); // 补零
  return `${year}-${month}-${day}`; // 时间部分设置为00:00:00
};

const selectLabel = (index) => {
  // console.log(index); // 确认点击事件是否触发
  selectedLabel.value = index;

  const currentDate = new Date();

  // 根据选择的标签打印对应的日期
  switch (index) {
    case 0: // 昨日
      const yesterday = new Date(); // 昨天日期
      yesterday.setDate(currentDate.getDate() - 1);
      begin.value = end.value = formatDateToString(yesterday);
      break;
    case 1: // 7日
      const sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(currentDate.getDate() - 7);
      currentDate.setDate(currentDate.getDate() - 1);
      begin.value = formatDateToString(sevenDaysAgo);
      end.value = formatDateToString(currentDate);
      break;
    case 2: // 30日
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(currentDate.getDate() - 30);
      currentDate.setDate(currentDate.getDate() - 1);
      begin.value = formatDateToString(thirtyDaysAgo);
      end.value = formatDateToString(currentDate);
      break;
    case 3: // 本周 (星期一到星期天)
      const startOfWeek = new Date(currentDate);
      // 将日期设置为本周一
      startOfWeek.setDate(currentDate.getDate() - (currentDate.getDay() === 0 ? 6 : currentDate.getDay() - 1));
      begin.value = formatDateToString(startOfWeek);

      const endOfWeek = new Date(currentDate);
      // 将日期设置为本周日
      endOfWeek.setDate(startOfWeek.getDate() + 6);
      end.value = formatDateToString(endOfWeek);
      break;
    case 4: // 本月
      const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
      const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
      begin.value = formatDateToString(firstDayOfMonth);
      end.value = formatDateToString(lastDayOfMonth);
      break;
  }

  // console.log(`开始时间：${begin.value}`);
  // console.log(`结束时间：${end.value}`);

  // 请求营业额统计数据
  fetchTurnoverStatistics(); // 添加数据请求调用
  // 请求用户统计数据
  fetchUserStatistics();
  // 请求订单统计数据
  fetchOrdersStatistics();
  // 请求TOP10预约统计数据
  fetchTop10();
};

// 营业额统计
const RevenueStatistics = ref({
  xAxisData: [],
  seriesData: [],
})
const fetchTurnoverStatistics = async () => {
  try {
    const response = await turnoverStatistics(
      begin.value,
      end.value
    );
    // console.log(response);
    // 假设response.data包含所需的图表数据
    RevenueStatistics.value.xAxisData = response.data.dateList.split(',');
    RevenueStatistics.value.seriesData = response.data.turnoverList.split(',').map(Number);
    // 更新图表
    initChart();
  } catch (error) {
    console.error("获取营业额统计数据失败", error);
  }
}
function initChart() {
  const chartDom = document.getElementById('chart-container');

  // 检查并销毁已有的图表实例
  if (echarts.getInstanceByDom(chartDom)) {
    echarts.dispose(chartDom);
  }
  const myChart = echarts.init(chartDom, null, {
    renderer: 'canvas',
    useDirtyRect: false
  });



  const option = {
    title: {
      text: '营业额统计'
    },
    tooltip: {
      trigger: 'axis'
    },
    toolbox: {
      show: true,
      feature: {
        dataView: { readOnly: false },
        magicType: { type: ['line', 'bar'] },
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: RevenueStatistics.value.xAxisData // 使用获取的数据
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} $'
      }
    },
    series: [
      {
        type: 'line',
        data: RevenueStatistics.value.seriesData, // 使用获取的数据
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: 'Avg' }]
        }
      }
    ]
  };

  if (option && typeof option === 'object') {
    myChart.setOption(option);
  }
}

// 用户统计
const UserStatistics = ref({})
const fetchUserStatistics = async () => {
  try {
    const response = await userStatistics(begin.value, end.value);
    // console.log(response);
    // 假设response.data包含所需的图表数据
    UserStatistics.value = response.data;
    // 更新图表
    initUserChart();
  } catch (error) {
    console.error("获取用户统计数据失败", error);
  }

}
function initUserChart() {
  const chartDom = document.getElementById('usermain');
  // 如果已有图表实例，则先销毁该实例
  if (echarts.getInstanceByDom(chartDom)) {
    echarts.dispose(chartDom);
  }
  const myChart = echarts.init(chartDom);
  // option 设置
  const option = {
    title: {
      text: '用户统计'
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#fff',
      borderRadius: 2,
      textStyle: {
        color: '#333',
        fontSize: 12,
        fontWeight: 300,
      },
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLabel: {
        color: '#666',
        fontSize: '12px'
      },
      axisLine: {
        lineStyle: {
          color: '#E5E4E4',
          width: 1,
        },
      },
      data: UserStatistics.value.dateList.split(','),
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        color: '#666',
        fontSize: '12px'
      },
    },
    series: [
      {
        name: '用户总量',
        type: 'line',
        smooth: false,
        showSymbol: false,
        lineStyle: {
          color: '#FFD000',
        },
        itemStyle: {
          color: '#FFD000',

        },
        emphasis: {
          color: '#fff',
          borderWidth: 5,
          borderColor: '#FFC100',
        },
        data: UserStatistics.value.totalUserList.split(',').map(Number),
      },
      {
        name: '新增用户',
        type: 'line',
        smooth: false,
        showSymbol: false,
        lineStyle: {
          color: '#FD7F7F',
        },
        itemStyle: {
          color: '#FD7F7F',

        },
        emphasis: {
          color: '#fff',
          borderWidth: 5,
          borderColor: '#FD7F7F',
        },
        data: UserStatistics.value.newUserList.split(',').map(Number),
      },
    ],
  };

  // 使用刚指定的配置项和数据显示图表
  myChart.setOption(option);
}

// 订单统计
const OrderStatistics = ref({})
const fetchOrdersStatistics = async () => {
  try {
    const response = await ordersStatistics(begin.value, end.value);
    // console.log(response);
    OrderStatistics.value = response.data;
    // console.log(OrderStatistics.value);
    // 更新图表
    initOrderChart();
  } catch (error) {
    console.error("获取订单统计数据失败", error);
  }
}
function initOrderChart() {
  const chartDom = document.getElementById('ordermain');
  if (echarts.getInstanceByDom(chartDom)) {
    echarts.dispose(chartDom);
  }
  const myChart = echarts.init(chartDom);
  var option = {
    title: {
      text: '订单统计',
      subtext: `订单完成率: ${(OrderStatistics.value.orderCompletionRate * 100).toFixed(2)}%`,
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#fff',
      borderRadius: 2,
      textStyle: {
        color: '#333',
        fontSize: 12,
        fontWeight: 300,
      },
    },
    grid: {
      top: '15%',
      left: '20',
      right: '50',
      bottom: '12%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLabel: {
        color: '#666',
        fontSize: '12px'
      },
      axisLine: {
        lineStyle: {
          color: '#E5E4E4',
          width: 1,
        },
      },
      data: OrderStatistics.value.dateList.split(','), // 使用示例生成的数据
    },
    yAxis: {
      type: 'value',
      min: 0,
      interval: 10,
      axisLabel: {
        color: '#666',
        fontSize: '12px'
      },
    },
    series: [
      {
        name: '订单总数',
        type: 'line',
        smooth: false,
        showSymbol: false,
        lineStyle: {
          color: '#FFD000',
        },
        itemStyle: {
          color: '#FFD000',

        },
        emphasis: {
          color: '#fff',
          borderWidth: 5,
          borderColor: '#FFC100',
        },
        data: OrderStatistics.value.orderCountList.split(',').map(Number), // 使用示例生成的数据
      },
      {
        name: '有效订单',
        type: 'line',
        smooth: false,
        showSymbol: false,
        lineStyle: {
          color: '#FD7F7F',
        },
        itemStyle: {
          color: '#FD7F7F',
        },
        emphasis: {
          color: '#fff',
          borderWidth: 5,
          borderColor: '#FD7F7F',
        },
        data: OrderStatistics.value.validOrderCountList.split(',').map(Number), // 使用示例生成的数据
      },
    ],
  };

  // 使用刚指定的配置项和数据显示图表
  myChart.setOption(option);
}

// 预约统计排名TOP10
const Top10 = ref({})
const fetchTop10 = async () => {
  try {
    const response = await top10(begin.value, end.value);
    // console.log(response);
    Top10.value = response.data;
    // console.log(Top10.value);
    // 更新图表
    initTopChart();
  } catch (error) {
    console.error("获取预约统计排名TOP10数据失败", error);
  }
}
function initTopChart() {
  // 设置图表类型
  const chartDom = document.getElementById('top');
  const myChart = echarts.init(chartDom);

  // 生成示例数据
  const nameList = [];
  const numberList = [];
  for (let i = 0; i < 10; i++) {
    nameList.push(`项目 ${i + 1}`); // 生成项目名称
    numberList.push(Math.floor(Math.random() * 100)); // 生成随机数量
  }
  // console.log("nameList",nameList);
  // console.log("numberList",numberList);

  // 图表选项
  var option = {
    title: {
      text: '排名TOP10',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#fff',
      borderRadius: 2,
      textStyle: {
        color: '#333',
        fontSize: 12,
        fontWeight: 300,
      },
    },
    grid: {
      top: '15%',
      left: '20',
      right: '20',
      bottom: '2%',
      containLabel: true,
    },
    xAxis: {
      show: false,
    },
    yAxis: {
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
        alignWithLabel: true,
      },
      type: 'category',
      axisLabel: {
        color: '#666',
        fontSize: '12px',
      },
      data: Top10.value.nameList.split(','), // 使用示例生成的名称数据
    },
    series: [
      {
        data: Top10.value.numberList.split(',').map(Number), // 使用示例生成的数量数据
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: '#F3F4F7',
        },
        barWidth: 20,
        barGap: '80%',
        barCategoryGap: '80%',

        itemStyle: {
          borderRadius: [0, 10, 10, 0],
          color: new echarts.graphic.LinearGradient(
            1,
            0,
            0,
            0,
            [
              { offset: 0, color: '#FFBD00' },
              { offset: 1, color: '#FFD000' },
            ]
          )
        },
        emphasis: {
          borderRadius: 30,
        },
      },
    ],
  };

  // 使用配置项和数据显示图表
  myChart.setOption(option);
}



// 使用onMounted来调用initChart函数
onMounted(async () => {
  selectLabel(selectedLabel.value);

});


</script>

<style>
.el-row {
  margin-bottom: 10px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.yesterday-label {
  border-radius: 4px;
  min-height: 36px;
  background-color: #e6e6e6;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  /* 添加指针样式 */
  transition: background-color 0.3s;
  /* 添加过渡效果 */
}

.yesterday-label.active {
  background-color: #D8E699;
}

.selected-time {
  border-radius: 4px;
  min-height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.export-btn {
  margin-left: -15px;
}

.export-btn:hover {
  background-color: #D8E699;
  color: #000;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  background-color: #fff;
  height: 430px;
  padding-top: 30px;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>
